<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Buy extends Auth
{
    public function __construct(Request $request){
        parent::__construct($request);  
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    // 采购计划列表
    public function plan(Request $request)
    {   
        if($request->isAjax()){
            // 当搜索时，是获取全部时间段数据
            if(isset($this->data['searchText']) && $this->data['searchText']){
                $where['mp.content|cp.name'] = ['like','%'.$this->data['searchText'].'%'];
            }else{
                $delivery_at_start = isset($this->data['year']) && isset($this->data['month']) ? mktime(0,0,0,date($this->data['month']),1,date($this->data['year'])) : strtotime(date('Y-m-01'));
                $delivery_at_end = isset($this->data['year']) && isset($this->data['month']) ? mktime(23,59,59,date($this->data['month']),date('t'),date($this->data['year'])) :  mktime(23,59,59,date('m'),date('t'),date('Y'));
                $where['zu.delivery_at'] = ['between',$delivery_at_start.','.$delivery_at_end];
            }
            if(isset($this->data['plan_ids']) && $this->data['plan_ids']) $where['zu.id'] = ['not in',$this->data['plan_ids']]; 
            $where['zu.po_id'] = 0;
            $where['zu.is_item'] = $this->data['item'];
            // return $where;
            $plan = model('Buy')->getBuyPlan($where,$this->lang);
            if(!empty($plan)){
                foreach ($plan as $k => $v) {
                    $plan[$k]['delivery_time'] = explode(' ',getTimeDates($v['delivery_at'],9,$this->lang))[0];
                }
            }
            // dump($plan);die;
            return json_encode(array('status'=>1,'data'=>$plan));
        }else{
            return view('plan');
        }
    }

    function getOrganizData($data)
    {
        unset($this->data['data']['proval']);
        $this->data['data']['delivery_at']   = strtotime($this->data['data']['delivery_at']);
        $this->data['data']['is_item']   = getValue('pro',['id'=>$data['data']['pro_id']],'is_item');
        if(isset($this->data['norm'])){
            $this->data['data']['ctn_kgs']   = $data['norm']['ctn_kgs'];
            $this->data['data']['ctn_m3']    = $data['norm']['ctn_m3'];
            $this->data['data']['ctn_size']  = $data['norm']['ctn_size'];
            $this->data['data']['ctn_qty']   = $data['norm']['qty'];
        }
    }

    // 添加新采购计划
    public function plan_addnew(Request $request)
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            $pro = getValue('multi_lang',['mkey'=>'pro_'.$this->data['data']['pro_id'],'lang'=>$this->lang],'content');
            $prochar = getValue('prochar',['id'=>$this->data['data']['prochar_id']],'model');

            $noticeText = noticeText($this->data['data'],['buy_id'=>lang('designated_buyer'),'delivery_at'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'qty'=>lang('purchase_quantity_'),'pro_id'=>lang('product'),'price'=>lang('purchase_prices')]);
            if(!empty($noticeText)) return json_encode($noticeText);
            $this->getOrganizData($this->data);

            $this->data['data']['create_id'] = $this->user_id;
            $this->data['data']['create_at']= time();
            // return $this->data['pro_item'];
            unset($this->data['data']['proval']);
            $buy_plan_id = insertData('buy_plan',$this->data['data']);
            if(!$buy_plan_id) return json_encode(array('status'=>0,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_addition_failed')));

            if(!empty($this->data['pro_item'])){
                $res = model('Buy')->insertPlan2item($this->data,$buy_plan_id,'add');
                if($res == 500) return json_encode(array('status'=>0,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('parts_planned_order_addition_failed')));
            }

            if(!empty($this->data['prodesc_cat'])){
                foreach ($this->data['prodesc_cat'] as $k1 => $v1) {
                    $buy_plan_remarks['buy_plan_id'] = $buy_plan_id;
                    $buy_plan_remarks['content'] = $v1['content'];
                    $buy_plan_remarks['prodesc_cat_id'] = $v1['id'];
                    $buy_plan_remarksinsert = insertData('buy_plan_remarks',$buy_plan_remarks);
                }
            }
            return json_encode(array('status'=>1,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_added_successfully')));
        }else{
            if($request->isAjax()){
                // 产品分类
                $procat = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
                $procat = getTree($procat);
                // dump($procat);die;
                // 采购人员
                $buy_persion = getDatas('admin',['id,nickname'],['position_id'=>18]);
                // dump($buy_persion);die;
                // 交货地址
                $port = getDatas('port',['id,name'],'1=1','id desc');

                $returnData['procat'] = $procat;
                $returnData['buy_persion'] = $buy_persion;
                $returnData['port'] = $port;
                return json_encode($returnData);
            }else{
                return view('plan_addnew',['title'=>lang('purchase_plan_added'),'request'=>'add']);
            }
        }
        
    }


    // 将计划订单移除合同
    public function delPlanForPo()
    {   
        // 移除前获取其绑定的合同po_id
        $po_id = getValue('buy_plan',['id'=>$this->data['id']],'po_id');
        $res = updateData('buy_plan',['id'=>$this->data['id']],['po_id'=>0]);
        $res = model('Buy')->updatePo($po_id,$this->user_id);
        return 2000;
    }

    // 整理编辑数据
    function OrganizEditData()
    {
        $id = $this->data['id'];
        $method = '';
        if(isset($this->data['method'])) $method = $this->data['method'];
        $prodesc_cat = isset($this->data['planInfo']['prodesc_cat']) ? $this->data['planInfo']['prodesc_cat'] : [];
        unset($this->data['planInfo']['prodesc_cat']);
        $data['buy_id']     = $this->data['planInfo']['buy_id'];
        $data['company_id'] = $this->data['planInfo']['company_id'];
        $data['create_id']  = $this->data['planInfo']['create_id'];
        $data['create_at'] = $this->data['planInfo']['create_at'];
        $data['ctn_kgs']    = $this->data['planInfo']['ctn_kgs'];
        $data['ctn_m3']     = $this->data['planInfo']['ctn_m3'];
        $data['ctn_qty']    = $this->data['planInfo']['ctn_qty'];
        $data['ctn_size']   = $this->data['planInfo']['ctn_size'];
        $data['del_at']     = $this->data['planInfo']['del_at'];
        $data['del_id']     = $this->data['planInfo']['del_id'];
        $data['delivery_at']= date("Y-m-d",$this->data['planInfo']['delivery_at']);
        $data['price']      = $this->data['planInfo']['price'];
        $data['qty']        = $this->data['planInfo']['qty'];
        $data['pro_id']     = $this->data['planInfo']['pro_id'];
        $data['prochar_id'] = $this->data['planInfo']['prochar_id'];
        $data['port_id']    = $this->data['planInfo']['port_id'];
        $data['po_id']      = $this->data['planInfo']['po_id'];
        $data['update_id']  = $this->user_id;
        $data['update_at'] = time();
        $this->data = [];
        $this->data['id'] = $id;
        $this->data['data'] = $data;
        $this->data['method'] = $method;
        $this->data['prodesc_cat'] = $prodesc_cat;
        $this->data['pro_item'] = getDatas('buy_plan2item',['*'],['buy_plan_id'=>$this->data['id']]);
    }


    public function plan_editnew(Request $request){
        if(!isset($this->data['id'])) return json_encode(array('status'=>2,'msg'=>lang('select_planned_order_to_edit')));
        if(isset($this->data['request']) && $this->data['request'] == 'update'){
            if(!isset($this->data['data'])) $this->OrganizEditData($this->data);
            $pro = getValue('multi_lang',['mkey'=>'pro_'.$this->data['data']['pro_id'],'lang'=>$this->lang],'content');
            $prochar = getValue('prochar',['id'=>$this->data['data']['prochar_id']],'model');
            // 整理数据
            $noticeText = noticeText($this->data['data'],['buy_id'=>lang('designated_buyer'),'delivery_at'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'qty'=>lang('purchase_quantity_'),'pro_id'=>lang('product'),'price'=>lang('purchase_prices')]);
            if(!empty($noticeText)) return json_encode($noticeText);
            $this->getOrganizData($this->data);
            // return $this->data['pro_item']['0']['buy_plan_item_id'];
            $this->data['data']['update_id'] = $this->user_id;
            $this->data['data']['update_at']= time();
            $buy_plan_id = updateData('buy_plan',['id'=>$this->data['id']],$this->data['data']);
            if(!$buy_plan_id) return json_encode(array('status'=>0,'msg'=>lang('prodect').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_edit_failed')));

            dump($this->data);die;
            if(!empty($this->data['pro_item'])){
                $res = model('Buy')->insertPlan2item($this->data,$this->data['id'],'update');
            }

            if(!empty($this->data['prodesc_cat'])){
                foreach ($this->data['prodesc_cat'] as $k1 => $v1) {
                    $buy_plan_remarks['buy_plan_id'] = $this->data['id'];
                    $buy_plan_remarks['content'] = $v1['content'];
                    $buy_plan_remarks['prodesc_cat_id'] = $v1['id'];
                    $buy_plan_remarksinsert = updateData('buy_plan_remarks',['id'=>$v1['buy_plan_remarks_id']],$buy_plan_remarks);
                }
            }
            // 是否是编辑采购合同状态,修改合同信息
            if(isset($this->data['method']) && $this->data['method'] == 'buy_po_edit'){
                $res = model('Buy')->updatePo($this->data['data']['po_id'],$this->user_id);
            }
            return json_encode(array('status'=>1,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_edited_successfully')));
        }else{
            if($request->isAjax()){
                $plan = model('Buy')->getBuyPlan(['zu.id'=>$this->data['id']],$this->lang);
                if(!empty($plan)){
                    $plan[0]['delivery_at'] = explode(' ',getTimeDates($plan[0]['delivery_at'],9,$this->lang))[0];

                    $feature = model('Buy')->getFeature($plan[0]['pro_id'],$plan[0]['prochar_id'],$this->lang);
                    $plan[0]['feature'] = '';
                    $plan[0]['feature'] .= $plan[0]['prochar_id']. '/'.$plan[0]['brand_name'].'/'.$plan[0]['model'].'/'.$plan[0]['pro_name'];
                    if(!empty($feature)){
                        foreach ($feature as $k1 => $v1) {
                            $plan[0]['feature'] .= '/'.$v1['value'];
                        }
                    }

                    // 产品分类
                    $procat = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
                    $returnData['procat'] = getTree($procat);
                    // 采购人员
                    $returnData['buy_persion'] = getDatas('admin',['id,nickname'],['position_id'=>18]);
                    // 全部公司信息
                    $returnData['company'] = model('Buy')->searchCompany();

                    // 获取产品和产品角色的基本信息
                    $returnData['proAndProchar'] = model('Buy')->getProAndProchar($plan[0]['pro_id'],$plan[0]['prochar_id'],$this->lang);

                    // 获取产品/产品角色下的介绍类型 内容
                    $returnData['prodesc_cat'] = getSearch('buy_plan_remarks','zu',['zu.id buy_plan_remarks_id,zu.prodesc_cat_id id,zu.content,mc.content name'],['zu.buy_plan_id'=>$plan[0]['id'],'mc.lang'=>$this->lang],[['prodesc_cat pc','zu.prodesc_cat_id = pc.id'],['multi_lang mc','pc.mkey = mc.mkey']],'zu.id asc');

                    // 获取产品/产品角色配件信息
                    $pro_item = model('Buy')->getPro_item($plan[0]['pro_id'],$plan[0]['prochar_id'],$this->lang);
                    foreach ($pro_item as $k2 => $v2) {
                        $pro_item[$k2]['qty'] = getValue('buy_plan2item',['pro_item_id'=>$v2['id'],'buy_plan_id'=>$plan[0]['id']],'plan_item_qty');
                        $pro_item[$k2]['buy_plan_item_id'] = getValue('buy_plan2item',['pro_item_id'=>$v2['id'],'buy_plan_id'=>$plan[0]['id']],'id');
                    }

                    // 装箱规格
                    // $norm = getDatas('buy_plan',['ctn_size,ctn_kgs,ctn_m3,ctn_qty qty,qty_sum,price_sum,m3_sum,kgs_sum'],['id'=>$this->data['id']],'id desc');
                    $norm = model('Buy')->getOrganizNorm($plan[0]);

                    // 历史记录
                    $history = getSearch('buy_plan','zu',['zu.po_id,zu.company_id,zu.qty,zu.price,zu.create_at,c.name'],['zu.po_id'=>['>',0],'zu.prochar_id'=>$plan[0]['prochar_id']],[['company c','zu.company_id = c.id']],'zu.id desc');
                    if(!empty($history)){
                        foreach ($history as $k => $v) {
                            $history[$k]['create_at'] = explode(' ',getTimeDates($v['create_at'],9,$this->lang))[0];
                        }
                    }

                    // 交货地址
                    $returnData['port'] = getDatas('port',['id,name'],'1=1','id desc');

                    // 拆分产品信息
                    $returnData['prolist'][0] = ['pro_id'=>$plan[0]['pro_id'],'id'=>$plan[0]['prochar_id'],'feature'=>$plan[0]['feature']];
                    $returnData['planlist'] = $plan[0];
                    $returnData['price'] = $plan[0]['price'];
                    $returnData['pro_item'] = $pro_item;
                    $returnData['history'] = $history;
                    $returnData['norm'] = !empty($norm) ? $norm : [];
                }else{
                    $returnData = [];
                }
                // dump($returnData);die;
                return json_encode($returnData);
                
            }else{
                return view('plan_addnew',['title'=>lang('edit_purchase_plan'),'request'=>'edit','plan_id'=>$this->data['id']]);
            }
        }
    }

    // 采购计划生成合同
    public function plan2po(Request $request)
    {   
        if(!isset($this->data['plan_ids']) && $this->data['plan_ids'] == '') return json_encode(array('status'=>2,'msg'=>lang('please_check_the_product_or_accessory_purchase_plan'))); // 请勾选产品或者配件采购计划
        if($request->isAjax()){
            $plan_ids = explode(',', $this->data['plan_ids']);
            $returnData = model('Buy')->geyBuyPoInfo($plan_ids,$this->data['po_id'],$this->data['request']);
            // dump($returnData);die;
            return json_encode($returnData);
        }else{
            return view('plan2po',['plan_ids'=>$this->data['plan_ids'],'title'=>lang('purchase_plan_generation_contract'),'request'=>'add']);
        }
    }


    // 采购计划删除
    public function buy_planDel()
    {
        if(!isset($this->data['ids']) || empty($this->data['ids'])) return json_encode(array('status'=>2,'msg'=>lang('please_select_a_planned_order_to_delete')));  // 请选择要删除的计划订单

        $pro = '';
        $prochar = '';
        foreach ($this->data['ids'] as $k => $v) {
            $plan = getDatas('buy_plan',['pro_id','prochar_id','po_id'],['id'=>$v]); 
            if(empty($plan)) return json_encode(array('status'=>2,'msg'=>lang("the_current_planned_order_doesn't_exist_ou_has_been_deleted")));   // 当前计划订单不存在或者已被删除
            if($k < 3){
                $pro .= ','.getValue('multi_lang',['mkey'=>'pro_'.$plan[0]['pro_id'],'lang'=>$this->lang],'content');
                $prochar .= ','.getValue('prochar',['id'=>'prochar_'.$plan[0]['prochar_id']],'model');
            }
            if($k = 3){
                $pro .= '...';
                $prochar .= '...';
            } 
            
            if($plan[0]['po_id'] > 0) return json_encode(array('status'=>2,'msg'=>lang('serial_number').'：'.$v.','.lang('product').'：'.getValue('multi_lang',['mkey'=>'pro_'.$plan[0]['pro_id'],'lang'=>$this->lang],'content').','.lang('model').'：'.getValue('prochar',['id'=>'prochar_'.$plan[0]['prochar_id']],'model').','.lang("can't_be_deleted_as_a_contract_order"))); // 已成为合同订单无法删除

            $res = deleteData('buy_plan',['id'=>$v]);
            if($res){
                $buy_plan_id2item = getDatas('buy_plan2item',['buy_plan_id2item'],['buy_plan_id'=>$v]);
                // 获取当前计划订单下的所有配件订单信息
                if(!empty($buy_plan_id2item)){
                    $res1 = deleteData('buy_plan2item',['buy_plan_id'=>$v]);
                    foreach ($buy_plan_id2item as $k1 => $v1) {
                        $res2 = deleteData('buy_plan',['id'=>$v1['buy_plan_id2item']]);
                    }
                }
                $res2 = deleteData('buy_plan_remarks',['buy_plan_id'=>$v]);
            }
        }
        ltrim($pro,',');
        ltrim($prochar,',');
        if($res){
            return json_encode(array('status'=>1,'msg'=>lang('serial_number').'：'.$v.','.lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('cleared_successfully')));
        }else{
            return json_encode(array('status'=>0,'msg'=>lang('serial_number').'：'.$v.','.lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('edit_failed')));
        }
    }

    public function addBuyPoToPlan()
    {
        if(!isset($this->data['data'])) $this->OrganizEditData($this->data);
        $pro = getValue('multi_lang',['mkey'=>'pro_'.$this->data['data']['pro_id'],'lang'=>$this->lang],'content');
        $prochar = getValue('prochar',['id'=>$this->data['data']['prochar_id']],'model');
        // 整理数据
        $noticeText = noticeText($this->data['data'],['buy_id'=>lang('designated_buyer'),'delivery_at'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'qty'=>lang('purchase_quantity_'),'pro_id'=>lang('product'),'price'=>lang('purchase_prices')]);
        if(!empty($noticeText)) return json_encode($noticeText);
        $this->getOrganizData($this->data);
        $this->data['data']['po_id'] = 0;
        $this->data['data']['update_id'] = $this->user_id;
        $this->data['data']['update_at']= time();
        $buy_plan_id = updateData('buy_plan',['id'=>$this->data['id']],$this->data['data']);
        if(!$buy_plan_id) return json_encode(array('status'=>0,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_edit_failed')));
        if(!empty($this->data['pro_item'])){
            $res = model('Buy')->insertPlan2item($this->data,$this->data['id'],'update');
        }

        if(!empty($this->data['prodesc_cat'])){
            foreach ($this->data['prodesc_cat'] as $k1 => $v1) {
                $buy_plan_remarks['buy_plan_id'] = $this->data['id'];
                $buy_plan_remarks['content'] = $v1['content'];
                $buy_plan_remarks['prodesc_cat_id'] = $v1['id'];
                $buy_plan_remarksinsert = updateData('buy_plan_remarks',['id'=>$v1['buy_plan_remarks_id']],$buy_plan_remarks);
            }
        }
        // 是否是编辑采购合同状态,修改合同信息
        if(isset($this->data['method']) && $this->data['method'] == 'buy_po_edit'){
            $res = model('Buy')->updatePo($this->data['data']['po_id'],$this->user_id);
        }
        return json_encode(array('status'=>1,'msg'=>lang('product').'：'.$pro.','.lang('model').'：'.$prochar.' '.lang('planned_order_edited_successfully')));
    }
}